import json
from hashlib import md5

from django.core.paginator import Paginator
from django.http import HttpResponse, JsonResponse

# Create your views here.
from django.shortcuts import render, redirect
from django.urls import reverse

from admins.models import TUser, TRole


# 跳转到用户管理页面
from cloudLibraryDjango import common


def getList(request):
    userName = request.session.get("user_name")
    return render(request, 'users/list.html', locals())


# 查询用户列表，带分页
def list(request):
    # 表格要展现的数据
    users = TUser.objects.all()
    # 处理成LayUi官方文档的格式
    lis = commonList(users)

    res = common.getPageData(request, users, lis)
    result = common.getResult(users.count(), res)
    return HttpResponse(json.dumps(result))
    # return JsonResponse(result)


def searchList(request):
    # 表格要展现的数据
    users = TUser.objects.all()

    userName = request.GET.get("userName")
    if userName:
        users = users.filter(user_name=userName)

    userStatus = request.GET.get("userStatus")
    if userStatus:
        users = users.filter(user_status=userStatus)

    res = commonList(users)

    # 放在一个列表里
    result = common.getResult(users.count(), res)
    return JsonResponse(result)


# 跳转到添加页面
def show_add(request):
    return render(request, 'users/add.html')


# 添加数据
def add(request):
    if request.POST:
        userName = request.POST.get("userName")

        userEmail = request.POST.get("email")

        password = request.POST.get("pwd")
        pwd = md5(str(password).encode()).hexdigest()

        roleId = request.POST.get("roleId")
        role = TRole.objects.filter(id=roleId).first()

        user = TUser(user_name=userName, user_email=userEmail, user_password=pwd, user_role=role, user_status='0')
        user.save()
        result = {"code": 0, "msg": "添加成功"}
        return JsonResponse(result)

    result = {"code": 1, "msg": "添加失败"}
    return JsonResponse(result)
    # return redirect(reverse("Users:getList"))


# 跳转到修改页面
def show_edit(request, userId):
    user = TUser.objects.get(user_id=userId)
    return render(request, 'users/edit.html', locals())


# 编辑
def edit(request):
    if request.POST:
        userId = request.POST.get("userId")
        user = TUser.objects.get(pk=userId)  # pk代表主键，也可以写成主键的字段id

        userName = request.POST.get("userName")
        user.user_name = userName

        userEmail = request.POST.get("email")
        user.user_email = userEmail

        password = request.POST.get("pwd")
        password2 = request.POST.get("oldPwd")
        if password != password2:
            pwd = md5(str(password).encode()).hexdigest()
            user.user_password = pwd

        roleId = request.POST.get("roleId")
        role = TRole.objects.filter(id=roleId).first()
        user.user_role = role

        user.save()
        result = {"code": 0, "msg": "修改成功"}
        return JsonResponse(result)

    result = {"code": 1, "msg": "修改失败"}
    return JsonResponse(result)


def delete(request):
    if request.POST:
        id = request.POST.get('id')
        user = TUser.objects.get(user_id=id)
        user.user_status = "1"
        user.save()
        # user.delete()

        result = {"code": 0, "msg": "变更用户状态成功"}
        return JsonResponse(result)

    result = {"code": 1, "msg": "变更用户状态失败"}
    return JsonResponse(result)


# 批量执行删除
def deletes(request):
    if request.POST:
        ids = json.loads(request.POST['ids'])

        user = TUser.objects.filter(user_id__in=ids)
        user.delete()

        result = {"code": 0, "msg": "删除用户成功"}
        return JsonResponse(result)

    result = {"code": 1, "msg": "删除用户失败"}
    return JsonResponse(result)


def commonList(users):
    res = []
    for user in users:
        data = dict()
        data['userId'] = user.user_id
        data['userName'] = user.user_name
        data['userEmail'] = user.user_email
        userStatus = user.user_status
        if userStatus == '0':
            status = "有效"
        else:
            status = "无效"
        data['userStatus'] = status
        data['userRole'] = user.user_role.role_name
        res.append(data)
    return res
